/*
 * @Author: wujian
 * @Date: 2023-01-11 13:05:55
 * @LastEditors: wujian
 * @LastEditTime: 2023-10-30 17:43:25
 * @FilePath: \vue-vite-qiankun-main\app-main\src\utils\mqtt.js
 * @Description: mqtt封装
 * @email: 281919544@qq.com
 * Copyright (c) 2023 by wujian 281919544@qq.com, All Rights Reserved.
 */

import * as mqtt from 'mqtt/dist/mqtt';

const { MODE } = import.meta.env;
let mqttUrl = '';
if (MODE === 'development') {
	mqttUrl = import.meta.env.VITE_MQTT_URL;
} else if (MODE === 'beta') {
	mqttUrl = 'ws://' + location.hostname + ':8083' + '/mqtt';
} else {
	mqttUrl = 'ws://' + location.hostname + ':39018' + '/mqtt';
}

if (window.appConfig && window.appConfig.mqttUrl) {
	mqttUrl = window.appConfig.mqttUrl;
}
export const mqttSocket = {
	url: mqttUrl,
	topic: '',
};

class Mqtt {
	constructor(connectUrl, options, publish, subscription, messageCallBack) {
		this.connectUrl = connectUrl;
		this.options = options;
		this.publish = publish;
		this.subscription = subscription;
		this.messageCallBack = messageCallBack;
		this.connect();
	}
	/**
	 * @author: wujian
	 * @description: 连接
	 * @return {*}
	 */
	connect() {
		try {
			this.client = mqtt.connect(this.connectUrl, this.options);
			this.onWatch();
		} catch (error) {
			console.log(error);
			console.log('创建mqtt失败');
		}
	}
	/**
	 * @author: wujian
	 * @description: 监听
	 * @return {*}
	 */
	onWatch() {
		this.client.on('connect', () => {
			console.log(new Date().getTime());
			console.log('连接成功!');
			this.doSubscribe();
		});
		this.client.on('error', (error) => {
			console.log('连接失败', error);
		});
		this.client.on('message', (topic, message) => {
			this.messageCallBack({ message, topic });
		});
	}
	/**
	 * @author: wujian
	 * @description: 订阅
	 * @return {*}
	 */
	doSubscribe() {
		const { topic, qos } = this.subscription;
		this.client.subscribe(topic, qos, (error, res) => {
			if (error) {
				console.log('Subscribe to topics error', error);
				return;
			}
			console.log('Subscribe to topics res', res);
		});
	}
	/**
	 * @author: wujian
	 * @param: payload 需要发送的消息
	 * @description: 发送消息
	 * @return {*}
	 */
	doPublish(payload) {
		const { topic, qos } = this.publish;
		this.client.publish(topic, payload, qos, (error) => {
			if (error) {
				console.log('Publish error', error);
			}
		});
	}
	/**
	 * @author: wujian
	 * @description: 断开连接
	 * @return {*}
	 */
	destroyConnection() {
		if (this.client.connected) {
			try {
				this.client.end();
				this.client = {
					connected: false,
				};
				console.log('Successfully disconnected!');
			} catch (error) {
				console.log('Disconnect failed', error.toString());
			}
		}
	}
}

// mqtt连接配置
export const mqttDefaultConnection = {
	url: mqttSocket.topic,
	options: {
		// keepAlive: 10,
		clean: true, // 是否保留会话
		connectTimeout: 15000, // 超时时间
		reconnectPeriod: 15000, // 重连时间间隔
		// 认证信息
		clientId: 'ifm_' + new Date().getTime() + Math.ceil(Math.random() * 1000),
		username: 'admin',
		password: 'Deer@18083%Service$',
	},
};
// mqtt订阅配置
export const mqttSubscription = {
	topic: mqttSocket.topic,
	qos: 2,
};
// mqtt发送配置
export const mqttPublish = {
	topic: mqttSocket.topic,
	qos: 2,
	payload: '',
};

export default Mqtt;
